<template>
  <div
    class="file-item"
    :class="{
      selected: isSelected,
      'drag-over': fileStore.dragOverItem?.name === item.name,
    }"
    tabindex="0"
    :draggable="false"
    @click.stop="handleSelect"
    @dblclick="fileOps.openItem(item)"
    @contextmenu.stop="handleContextMenu"
    @keydown="handleKeyDown"
    @dragover.prevent="dragDrop.handleDragOver($event, item)"
    @dragleave="dragDrop.handleDragLeave($event, item)"
    @drop.stop="dragDrop.handleDrop($event, item)"
  >
    <!-- 文件图标 - 图标始终可以拖拽 -->
    <div class="file-icon" :draggable="true" @dragstart="handleIconDragStart">
      <el-icon size="48">
        <component :is="getFileIcon(item)" />
      </el-icon>
    </div>

    <!-- 文件名 - 支持重命名 -->
    <div class="file-name">
      <input
        v-if="uiState.renamingItem.value?.name === item.name"
        v-model="uiState.newName.value"
        @blur="uiState.confirmRename"
        @keydown.enter="uiState.confirmRename"
        @keydown.esc="uiState.cancelRename"
        class="rename-input"
        ref="renameInput"
      />
      <span v-else>{{ item.name }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, computed } from "vue";
import {
  Folder,
  Document,
  Picture,
  VideoPlay,
  Headset,
} from "@element-plus/icons-vue";
import type { FileSystemItem } from "../types/fileSystem";
import { useFileStore } from "../stores/fileStore";
import { useFileOperations } from "../hooks/useFileOperations";
import { useUIState } from "../hooks/useUIState";
import { useDragAndDrop } from "../hooks/useDragAndDrop";
import { getFileTypeInfo } from "../utils/fileUtils";

interface Props {
  item: FileSystemItem;
}

const props = defineProps<Props>();

const fileStore = useFileStore();
const uiState = useUIState();
const fileOps = useFileOperations(uiState);
const dragDrop = useDragAndDrop();

// 计算属性：是否选中
const isSelected = computed(() => {
  const selected = fileStore.selectedItem;
  if (!selected) return false;
  // 使用名称和路径进行更精确的比较
  return selected.name === props.item.name && selected.type === props.item.type;
});

// 获取文件图标
const getFileIcon = (item: FileSystemItem) => {
  if (item.type === "folder") {
    return Folder;
  }

  if (item.extension) {
    const typeInfo = getFileTypeInfo(item.extension);
    switch (typeInfo.category) {
      case "image":
        return Picture;
      case "video":
        return VideoPlay;
      case "audio":
        return Headset;
      case "document":
        return Document;
      default:
        return Document;
    }
  }

  return Document;
};

// 处理右键菜单
const handleContextMenu = (event: MouseEvent) => {
  event.preventDefault();
  fileStore.selectItem(props.item);
  uiState.showContextMenu(event.clientX, event.clientY);
};

// 处理键盘事件
const handleKeyDown = (event: KeyboardEvent) => {
  // F2 重命名
  if (event.key === "F2") {
    event.preventDefault();
    uiState.startRename(props.item);
    // 下一帧聚焦输入框
    nextTick(() => {
      const input = document.querySelector(".rename-input") as HTMLInputElement;
      if (input) {
        input.focus();
        input.select();
      }
    });
    return;
  }

  // Enter 打开
  if (event.key === "Enter") {
    event.preventDefault();
    fileOps.openItem(props.item);
    return;
  }
};

// 处理选中
const handleSelect = () => {
  // 如果当前项已经选中，则取消选中；否则选中它
  if (isSelected.value) {
    fileStore.clearSelection();
  } else {
    fileStore.selectItem(props.item);
  }
};

// 统一的拖拽处理函数 - 图标始终可以拖拽
const handleIconDragStart = (event: DragEvent) => {
  dragDrop.handleDragStart(event, props.item);
};
</script>

<style scoped lang="scss">
// 导入样式变量
@import "../styles/explorer.scss";

.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  // 只过渡需要的属性，避免布局抖动
  transition:
    background-color 0.2s ease,
    box-shadow 0.2s ease;
  position: relative;
  // 彻底移除所有可能的边框和轮廓
  outline: none !important;
  border: none !important;
  box-shadow: 0 0 0 1px transparent;

  // 彻底移除所有可能的边框和轮廓，但允许hover状态的outline
  &,
  &:focus,
  &:active,
  &.selected {
    -webkit-tap-highlight-color: transparent;
  }

  // 默认状态：移除outline和border
  &:not(:hover):not(.drag-over) {
    outline: none !important;
    border: none !important;
  }

  // 选中时整体可拖拽
  &.selected {
    cursor: grab;

    &:active {
      cursor: grabbing;
    }
  }

  &:hover:not(.selected) {
    background: #f5f5f5;
  }

  &:focus:not(.selected) {
    background: var(--el-color-primary-light-9);
  }

  &.selected {
    background: var(--el-color-primary-light-8);
  }

  &.drag-over {
    background: var(--el-color-primary-light-8) !important;
    // 拖拽目标才显示边框
    box-shadow: inset 0 0 0 2px var(--el-color-primary) !important;
    position: relative;
    z-index: 10;
  }

  .file-icon {
    margin-bottom: 4px;
    cursor: default;

    // 彻底移除边框和轮廓
    outline: none !important;
    border: none !important;
  }

  // 未选中时图标可拖拽
  &:not(.selected) .file-icon {
    cursor: grab;

    &:active {
      cursor: grabbing;
    }
  }

  // 选中时的图标缩放已移除，避免布局变化

  .file-name {
    font-size: 12px;
    text-align: center;
    word-break: break-all;
    line-height: 1.3;
    max-width: 100px;
    @include user-select(text);
  }

  // 选中状态时，文件名区域也应该是拖拽光标
  &.selected .file-name {
    cursor: grab;
    @include user-select(none); // 选中时禁止文本选择，避免与拖拽冲突

    &:active {
      cursor: grabbing;
    }

    .rename-input {
      background: white;
      border: 1px solid var(--el-color-primary);
      border-radius: 3px;
      padding: 2px 4px;
      font-size: 12px;
      width: 100%;
      outline: none;

      &:focus {
        border-color: var(--el-color-primary);
        box-shadow: 0 0 0 2px var(--el-color-primary-light-7);
      }
    }
  }
}
</style>
